using System;
using System.Collections.Concurrent;
using System.IO;
using Google.Protobuf;
using HuaXianQu.ProtoBuffEx.Runtime.ProtoInterface;

namespace HuaXianQu.ProtoBuffEx.Runtimes
{
    public class ProtoDataCenter
    {
        private static Lazy<ProtoDataCenter> lazy = new Lazy<ProtoDataCenter>(() => new ProtoDataCenter());
        private static ProtoDataCenter Instance => lazy.Value;

        public static T GetData<T>() where T : IMessage
        {
            return Instance.GetDataByEntity<T>();
        }

        private ConcurrentDictionary<Type, IMessage> dateDcit = new();

        public T GetDataByEntity<T>() where T : IMessage
        {
            byte[] data = File.ReadAllBytes(
                $"{"Assets/Res/ProtoData/ProtoGen"}/{typeof(T).Name}.protodat");
            var value = dateDcit.GetOrAdd(typeof(T), (key) =>
            {
                var temp = Activator.CreateInstance<T>();
                temp = (T)temp.Descriptor.Parser.ParseFrom(data);
                (temp as IProtoInit)?.Init();
                return temp;
            });
            return (T)value;
        }
    }
}